from request import Request
from response import Response


class WSGIHandler:
    def __init__(self):
        self.urls = []

    def __call__(self, environ, start_response):
        request = Request(environ)
        response = Response()

        matched = False
        for path, method, func in self.urls:
            if (request.path, request.method) == (path, method):
                matched = True
                response.body = func(request, response)  # 响应体为func结果

        if not matched:
            response.status_code = 404
            response.body = 'Not Found!'

        # from wsgiref.simple_server import ServerHandler
        # ServerHandler.start_response
        start_response(response.status, response.headers)
        return [response.body]

    def route(self, path, method=None):
        if method is None:
            method = 'GET'

        def _wrapper(func):
            self.urls.append((path, method, func))

        return _wrapper

